'use strict';

const BaseController = require('./base.js');

class ManagerController extends BaseController {
  async index() {
    // 查询管理员表并管理角色表
    let result = await this.ctx.model.Admin.aggregate([{
        $lookup: {
            from: 'role',           // 关联角色表
            localField: 'role_id',  // 本表 id
            foreignField: '_id',    // 被关联表 id
            as: 'role'
        }
    }]);

    await this.ctx.render('admin/manager/index', {
        list: result
    })
  }

  async add() {
    // 获取角色
    let roleResult = await this.ctx.model.Role.find();
    await this.ctx.render('admin/manager/add', {
        roleResult
    })
  }

  async doAdd() {
    //console.log(this.ctx.request.body)
    let addResult = this.ctx.request.body;
    addResult.password = await this.service.tools.md5(addResult.password);   // 密码 MD5 加密

    // 判断提交的用户名是否已经存在
    let adminResult = await this.ctx.model.Admin.find({"username": addResult.username});

    if (adminResult.length > 0) {
      await this.error('/admin/manager/add', '此管理员已经存在')
    } else {
      var admin = new this.ctx.model.Admin(addResult);
      await admin.save();

      await this.success('/admin/manager', '增加用户成功')
    }
  }

  async edit() {
    // 获取编辑的数据
    const {ctx} = this;
    let id = this.ctx.request.query.id;

    let adminResult = await ctx.model.Admin.find({"_id":id});

    // 获取角色
    let roleResult = await this.ctx.model.Role.find();

    await this.ctx.render('admin/manager/edit', {
      adminResult: adminResult[0],
      roleResult: roleResult
    })
  }

  async doEdit() {
    //console.log(this.ctx.request.body)
    const {ctx} = this;
    let {id, mobile, email, role_id} = ctx.request.body;
    let password = ctx.request.body.password;

    if (password) {
      password = await this.service.tools.md5(password);
      await ctx.model.Admin.updateOne({"_id":id}, {password, mobile, email, role_id})
    } else {
      await ctx.model.Admin.updateOne({"_id":id}, {mobile, email, role_id})
    }

    await this.success('/admin/manager', '修改用户信息成功')
  }
}

module.exports = ManagerController;
